package com.doudanhua.basecode.mvc.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/9 20:42
 */
public final class RequestUtils {

    /**
     * 不区分大小写，读取QueryString查询参数。
     * 存在多个时，只返回第1个
     *
     * @param webRequest request
     * @param paraName   参数名
     * @return 值
     */
    public static String getParameter(HttpServletRequest webRequest, String paraName) {
        //return webRequest.getParameter(paraName);
        Enumeration<String> arr = webRequest.getParameterNames();
        while (arr.hasMoreElements()) {
            String realParaName = arr.nextElement();
            if (realParaName.equalsIgnoreCase(paraName)) {
                return webRequest.getParameter(realParaName);
            }
        }
        return "";
    }

    /**
     * 不区分大小写，读取Cookie参数
     * 存在多个时，只返回第1个
     *
     * @param httpServletRequest request
     * @param cookieName         参数名
     * @return 值
     */
    public static String getCookie(HttpServletRequest httpServletRequest, String cookieName) {
        assert httpServletRequest != null;

        Cookie[] arr = httpServletRequest.getCookies();
        if (arr == null) {
            return "";
        }
        for (Cookie cookie : arr) {
            if (cookie.getName().equalsIgnoreCase(cookieName)) {
                return cookie.getValue();
            }
        }
        return "";
        //return Arrays.stream(arr).filter(cookie -> cookie.getName().equalsIgnoreCase(cookieName)).map(Cookie::getValue).collect(Collectors.joining());
    }

    /**
     * 获取请求上下文的所有信息，用于日志
     *
     * @param request 请求
     * @return 信息
     */
    public static String getLog(HttpServletRequest request) {
        if (request == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder().append('\n');
        try {
            sb.append(request.getMethod()).append(" ").append(request.getRequestURI());
            sb.append(" headers:");
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String header = headerNames.nextElement();
                sb.append(header).append(':');
                Enumeration<String> headerValues = request.getHeaders(header);
                int valIdx = 0;
                while (headerValues.hasMoreElements()) {
                    if (valIdx > 0) {
                        sb.append(','); // 避免最后多一个逗号
                    }
                    valIdx++;
                    sb.append(headerValues.nextElement());
                }
                sb.append('&');
            }
        } catch (Exception exp) {
            sb.append(" getLogErr:").append(exp.getMessage());
        }
        return sb.toString();
    }

    /**
     * 获取当前请求上下文里的请求日志
     *
     * @return 信息
     */
    public static String getCurrentRequestLog() {
        RequestAttributes att = RequestContextHolder.getRequestAttributes();
        if (!(att instanceof ServletRequestAttributes)) {
            return "";
        }
        HttpServletRequest request = ((ServletRequestAttributes) att).getRequest();
        return getLog(request);
    }
}
